define(['angularAMD', 'moment'], function (angularAMD, moment) {
    angularAMD.service('$CheckOutService', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$calculater',
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater){
            var service = this;
            service.init = function(options){
                /**
                 * options = {
                 *     machine_no : string, //機台代號
                 *     item : object, //plot資料
                 *     callback : function //確定後呼叫
                 * }
                **/

                const plotInfo = options.item;

                // 物料用量初始��?
                function reCalcMaterialUseQty(sum_qty, dialog){
                    if(plotInfo.workstation_detail[0] && plotInfo.workstation_detail[0].materials_detail){
                        var materials_detail = plotInfo.workstation_detail[0].materials_detail;
                        var materialsMap = {};

                        for(var i = 0; i < materials_detail.length; i++){
                            var materials = materials_detail[i];

                            if(!materialsMap[materials.materials_no]){
                                var materialsList = $filter('filter')(materials_detail, {materials_no: materials.materials_no}, true);

                                if(materialsList.length > 0){
                                    var need_qty = +sum_qty; // 出站所需要的物料用量
                                    
                                    // 20200525 modify by WeiTing for M#72260 - 透過後台傳回參數 Num_Of_Decimal 調整小數點位數，一般是不開放調整的，除非有特殊需求才請後端直接調整資料庫。
                                    var Num_Of_Decimal = +plotInfo.Num_Of_Decimal;

                                    // 20201005 modify by WeiTing for M#67681 - 透過後台傳回參數 Close_DecreaseRate，判斷是否關閉損耗率(decrease_rate)計算。
                                    var Close_DecreaseRate = false;
                                    if(plotInfo.Close_DecreaseRate) {
                                        Close_DecreaseRate = true;
                                    }
                                    
                                    materialsList.forEach(function(item, index){
                                        // 物料實際耗用量 = 物料可用量 / 標準用料 / (1 + 損耗量)
                                        var real_use_qty = (((+item.available_qty) / (+item.std_use_qty)) / $calculater.decimalAdd(1, +item.decrease_rate));
                                        if(Close_DecreaseRate){
                                            real_use_qty = ((+item.available_qty) / (+item.std_use_qty));
                                        }

                                        if(+real_use_qty < +need_qty){
                                            // 物料預設使用量 = 可用量
                                            use_qty = (+item.available_qty); // 使用量結果
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            // 20201208 modify by WeiTing for M#82343 - 外包開發的，協助合併回主分支。
                                            item.use_qty = getUseqty(use_qty, Num_Of_Decimal, dialog.plotInfo.countMethod);
                                            need_qty = $calculater.decimalSub(+need_qty, +real_use_qty); // 更新出站所需要的物料用量
                                        } else {
                                            // 物料預設使用量 = 剩餘的物料所需用量 * 標準用量 * (1 + 損耗量)
                                            use_qty = $calculater.decimalMutiple($calculater.decimalMutiple(+need_qty, +item.std_use_qty), $calculater.decimalAdd(1, +item.decrease_rate)); // 使用量結果
                                            if(Close_DecreaseRate){
                                                use_qty = $calculater.decimalMutiple(+need_qty, +item.std_use_qty); // 使用量結果
                                            }
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            // 20201208 modify by WeiTing for M#82343 - 外包開發的，協助合併回主分支。
                                            item.use_qty = getUseqty(use_qty, Num_Of_Decimal, dialog.plotInfo.countMethod);
                                            need_qty = 0; // 出站所需要的物料用量已足夠
                                        }

                                        // 20200211 modify by WeiTing for M#66921 - 修改扣料順序邏輯：
                                        // 1. 主料存量優先扣除
                                        // 2. 替代料存量依序扣除
                                        // 3. 全部存量扣除完，需求量仍 > 0，則將量加回主料扣除量。（一般料與倒扣料一致）
                                        // 最後，出站所需要的物料用量仍不足夠，將仍不足的量加在第一筆物料(出站才會出現物料不足，不允許出站)
                                        if(index == (materialsList.length - 1) && +need_qty > 0){
                                            need_qty = $calculater.decimalMutiple($calculater.decimalMutiple(+need_qty, +materialsList[0].std_use_qty), $calculater.decimalAdd(1, +materialsList[0].decrease_rate)); 
                                            if(Close_DecreaseRate){
                                                need_qty = $calculater.decimalMutiple(+need_qty, +materialsList[0].std_use_qty);
                                            }
                                            use_qty = $calculater.decimalAdd(+materialsList[0].use_qty, +need_qty); // 使用量結果
                                            // 20200716 modify by WeiTing for M#74743 - 使用 toFixed 會有四捨五入的問題，所以改用 Math.floor 無條件捨去，才不會造成多扣使用量的問題。
                                            // 20201208 modify by WeiTing for M#82343 - 外包開發的，協助合併回主分支。
                                            materialsList[0].use_qty = getUseqty(use_qty, Num_Of_Decimal, dialog.plotInfo.countMethod);
                                        }
                                    });
                                }
                                materialsMap[materials.materials_no] = true;
                            }
                        }
                        const reworkMethod = dialog.plotInfo.reworkMethod || "1";
                        const reworkMaterialType = dialog.plotInfo.workstation_detail[0].rework_material_type || "0";
                        //M#96594 add by a991241234 修正重工批號  reworkMethod = 2 將物料使用量歸零
                        if(reworkMethod && reworkMethod == "2" && reworkMaterialType && reworkMaterialType ==  "1"){
                            plotInfo.workstation_detail[0].materials_detail.forEach(item => {
                                item.use_qty = 0;
                            });
                        }
                    }
                }

                // 20201208 modify by WeiTing for M#82343 - 外包開發的，協助合併回主分支。
                function getUseqty(use_qty, Num_Of_Decimal, countMethod){
                    if(countMethod == "1"){
                      return  Math.floor(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); // 調整使用量結果的小數點位數
                    }else if(countMethod == "2"){
                      return Math.ceil(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); 
                    }else if(countMethod == "3"){
                       return Math.round(+use_qty * Math.pow(10, +Num_Of_Decimal)) / Math.pow(10, +Num_Of_Decimal); 
                    }else{
                       return evenRound(use_qty, Num_Of_Decimal);
                    }
                }

                // 20201208 modify by WeiTing for M#82343 - 外包開發的，協助合併回主分支。
                function evenRound(num, decimalPlaces) {   
                    var d = decimalPlaces || 0;
                    var m = Math.pow(10, d);
                    var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
                    var i = Math.floor(n), f = n - i;
                    var e = 1e-8; // Allow for rounding errors in f
                    var r = (f > 0.5 - e && f < 0.5 + e) ?
                                ((i % 2 == 0) ? i : i + 1) : Math.round(n);
                    return d ? r / m : r;
                }
                //人員計價 出站 總額計算 add by a991241234 for M# 70310
                function getPriceSum()
                {
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    if(price_check_1 && price_check_2)
                    {
                        //20230519 modify by wangzy for M#0135983: 正式区出站报工计价计算错误
                        switch(plotInfo.price_type)
                        {
                            //計件
                            case "0":
                                if(isNaN(parseFloat(plotInfo.qty)) == false)
                                    plotInfo.price_sum = Number(parseFloat(plotInfo.qty) * parseFloat(plotInfo.price)).toFixed(2);
                            break;
                            //計時
                            case "1":
                                if(isNaN(parseFloat(plotInfo.workstation_detail[0].labor_hours)) == false)
                                    plotInfo.price_sum = Number(parseFloat(plotInfo.workstation_detail[0].labor_hours) * parseFloat(plotInfo.price)).toFixed(2);
                            break;
                        }
                    }
                }

                //人員計價 多人量產 總額計算 add by a991241234 for M# 70310
                function getPriceSumByLabor()
                {
                    //console.log(plotInfo.workstation_detail[0].labor_detail);
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    var price_check_3 = plotInfo.workstation_detail[0].labor_detail.length > 0;
                    if(price_check_1 && price_check_2 && price_check_3)
                    {
                        switch(plotInfo.price_type)
                        {
                            //計件
                            case "0":
                                var sum = 0;
                                for(var i in plotInfo.workstation_detail[0].labor_detail)
                                {
                                    var qty;
                                    if(isNaN(parseFloat(plotInfo.workstation_detail[0].labor_detail[i].qty)) == false)
                                        qty = plotInfo.workstation_detail[0].labor_detail[i].qty;
                                    else
                                        qty = plotInfo.workstation_detail[0].labor_detail[i].labor_qty;
                                    //20230519 modify by wangzy for M#0135983: 正式区出站报工计价计算错误
                                    plotInfo.workstation_detail[0].labor_detail[i].price_sum = Number(parseFloat(plotInfo.price) * parseFloat(qty)).toFixed(2);
                                    sum +=plotInfo.workstation_detail[0].labor_detail[i].price_sum;
                                }
                                if(sum > 0)
                                    //20221118 modify by wangqq for M#0120448:修正字符串转换错误
                                    plotInfo.price_sum = Number(sum).toFixed(2);
                            break;
                            //計時
                            case "1":
                                var sum = 0;
                                for(var i in plotInfo.workstation_detail[0].labor_detail)
                                {
                                    var time = plotInfo.workstation_detail[0].labor_detail[i].labor_time;
                                    //20230519 modify by wangzy for M#0135983: 正式区出站报工计价计算错误
                                    plotInfo.workstation_detail[0].labor_detail[i].price_sum = Number(parseFloat(plotInfo.price) * parseFloat(time)).toFixed(2);
                                    sum +=plotInfo.workstation_detail[0].labor_detail[i].price_sum;
                                }
                                if(sum > 0)
                                    plotInfo.price_sum = Number(sum).toFixed(2);
                            break;
                        }
                    }
                }

                //重構不良原因
                function genBadType(badReasonList){
                    var badTypeList = [];
                    var badType = '';
                    badReasonList.forEach(function(badReason){
                        if(badType!=badReason.reason_type){
                            badTypeList.push({
                                reason_type:badReason.reason_type,
                                reason_sub_type:badReason.reason_sub_type
                            });
                            badType = badReason.reason_type;
                        }
                    });
                    return badTypeList;
                }

                //模具檢查
                function AccLifeCheck(machine_no, dialog, callback){
                    var content = {
                        recordlist : [{
                            op_no: dialog.plotInfo.workstation_detail[0].op_no,
                            plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                            machine_no: machine_no,
                            status: '1',
                            qty: dialog.plotInfo.qty,
                        }
                    ]};
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_ACC.acc_life_check_process',
                        content : content,
                        success : function(data){
                            if(data.life_manage == '0'){
                                //警示
                                $rootScope.showConfirm(data.description, function(confirmDialog){
                                    confirmDialog.hide();
                                    if(callback)
                                        callback();
                                });
                            } else if(data.life_manage == '1'){
                                //暫停生產
                                $rootScope.showAlert(data.description);
                            } else if(data.life_manage == '2'){
                                //核准
                                if(callback)
                                    callback();
                            }
                        }
                    });
                }

                function ProductionParametersCheckProcess(dialog){
                    var content = {
                        handle_type : 'CHECK_OUT',
                        recordlist : [{
                            plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                            op_no: dialog.plotInfo.workstation_detail[0].op_no,
                            qty: dialog.plotInfo.qty,
                            abnormal_detail: dialog.plotInfo.workstation_detail[0].abnormal_detail
                        }]
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.production_parameters_check_process',
                        content: content,
                        success: function (data) {
                            checkRule(data.query_result, dialog);
                        }
                    });
                }

                //rule_result : WARNNING / WAIT / PASS
                //20170517 modify by Dustdusk for SMES_ProductionParametersCheckProcess調整回傳內容
                function checkRule(query_result, dialog){
                    var is_wait = false;
                    var warnning_msg = '';
                    query_result.forEach(function(plot_rule){
                        var plot_warnning_msg = '';
                        plot_rule.rule_detail.forEach(function(rule_detail){
                            if(rule_detail.rule_result == 'WARNNING'){
                                if(plot_warnning_msg == ''){
                                    plot_warnning_msg = plot_rule.plot_no + '<br>';
                                }
                                plot_warnning_msg += rule_detail.rule_message + '<br>';
                            } else if(rule_detail.rule_result == 'WAIT'){
                                is_wait = true;
                            }
                        });
                        warnning_msg += plot_warnning_msg;
                    });

                    if(warnning_msg != ''){
                        $rootScope.showConfirm(warnning_msg,
                            // 20230526 modify by Alan for#136593: 修正按下確認後無法出站的問題
                            function(confirmDialog){
                                confirmDialog.hide();
                                if(is_wait){
                                    //暫停原因
                                    dialog.wait_reason_detail.push({ reason_no: 'Z901' });
                                }
                                trackOutConfirm(dialog);
                            }
                        );
                    } else {
                        if(is_wait){
                            //暫停原因
                            dialog.wait_reason_detail.push({ reason_no: 'Z901' });
                        }
                        trackOutConfirm(dialog);
                    }
                }

                function trackOutConfirm(dialog) {
                    var abnormal_detail = [],
                        plot_info_detail= {},
                        materials_detail=[],
                        subop_employee_detail=[];

                    dialog.badItemList.forEach(function (item) {
                        abnormal_detail.push({
                            abnormal_no:item.abnormal_no,
                            defect_qty:item.defect_qty
                        });
                    });

                    dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function (item) {
                        subop_employee_detail.push({
                            employee_no:item.labor_no,
                            work_time: item.labor_time, // 20210819 modify by chenshibo for#98410：人时取值不对
                            qty: item.qty,
                            parameter_value: item.ParameterValue
                        });
                    });

                    dialog.plotInfo.materials_detail.forEach(function (item) {
                        if(item.putinplace_type == '5')
                            return;

                        materials_detail.push({
                            materials_no:item.materials_no,
                            materials_plot_no:item.materials_plot_no,
                            actual_use_qty:item.use_qty,

                        });
                    });

                    plot_info_detail = {
                        report_datetime: dialog.plotInfo.sysdate_time,
                        machine_no : options.machine_no, //
                        plot_no : dialog.plotInfo.workstation_detail[0].plot_no,
                        op_seq : dialog.plotInfo.workstation_detail[0].op_seq,
                        op_no : dialog.plotInfo.workstation_detail[0].op_no,
                        workstation_no : '',
                        qty:dialog.plotInfo.qty,
                        labor_hours : dialog.plotInfo.workstation_detail[0].labor_hours,
                        machine_hours : dialog.plotInfo.workstation_detail[0].machine_hours,
                        number_of_operators : dialog.plotInfo.workstation_detail[0].number_of_labor,
                        plot_stamp : dialog.plotInfo.workstation_detail[0].plot_stamp,
                        abnormal_detail : abnormal_detail,
                        subop_employee_detail : subop_employee_detail,
                        materials_detail : materials_detail,
                        wait_reason_detail : dialog.wait_reason_detail
                    };

                    var content = {
                        report_datetime: plot_info_detail.report_datetime,
                        check_out_mode: '1',
                        check_out_type: '2',
                        plot_info_detail:[plot_info_detail],
                        production_inf_detail: dialog.plotInfo.production_inf_detail
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_check_out_process',
                        content: content,
                        success: function (data, response) {
                            //$rootScope.showAlert(data.SysMsg, function(){
                            $rootScope.showToast(response.Message);
                                dialog.hide();
                                if(options.callback)
                                    options.callback();
                            //});
                        }
                    });
                }

                //^_^ADD BY H-10763  20200223 FOR 出站不良原因调整
                function loadBadNoList(bad_code_list,backFun)
                {
                    $mdDialog.dialog(
                           'module/moduleMobile/program/mobile01/BadTypeList.tmp.html',
                           function (BadTypeListDialog) {
                               return {
                                   bad_list: bad_code_list,
                                   dialog_hide:function(){
                                        BadTypeListDialog.hide();
                                   },
                                   back: function () {
                                       BadTypeListDialog.hide();
                                   },
                                   trackInputQty: function (event, item) {
                                       var target = event.currentTarget;
                                       angular.element(target).addClass('is-focus');
                                       $calculater.open(function (num, calcDialog) {
                                           item.qty = num;
                                           angular.element(target).removeClass('is-focus');
                                           calcDialog.hide();

                                       }, function (calcDialog) {
                                           angular.element(target).removeClass('is-focus');
                                           calcDialog.hide();
                                       },
                                       {
                                           defaultNum: item.qty,
                                           decimal: true
                                       });
                                   },
                                   confirm: function () {
                                       if (backFun){
                                           let pass_or_not = backFun(BadTypeListDialog.bad_list);
                                           if(pass_or_not){
                                                BadTypeListDialog.hide();
                                           }
                                       } 
                                   },
                               };
                           }
                       );
                }
                  //取得取消上下工資訊
                function equipmentBasisGet(callback) {
                    $MMWService.pageNumberInfoGet({
                        form_name: 'PageNo_60',
                        query_condition_info: [{column_name: 'EQUIPMENTNO', query_mode: '0', value: options.machine_no, merge_condition_model: 'AND' }]
                    }, function(itemList){
                        if(itemList.length > 0){
                            if(callback)
                                callback(itemList[0]);
                        }
                    });
                }

                //轉換率計��?
                function CaculatQTYACIO(qty, C_Numerator, C_Denominator) {
                    var QTYACIO = $calculater.decimalMutiple((+qty), (+C_Numerator) / (+C_Denominator)),
                        C_Mode = plotInfo.workstation_detail[0].C_Mode,
                        C_Accuracy = Math.pow(10, plotInfo.workstation_detail[0].C_Accuracy || 0) || 1;
                    if (C_Mode == '0') {
                        //無條件進位
                        QTYACIO = Math.ceil(QTYACIO * C_Accuracy) / C_Accuracy;
                    } else if (C_Mode == '1') {
                        //無條件捨��?
                        QTYACIO = Math.floor(QTYACIO * C_Accuracy) / C_Accuracy;
                    }
                    return QTYACIO;
                }

                //轉換率計��?
                function CaculatQTYACIO(qty, C_Numerator, C_Denominator) {
                    var QTYACIO = $calculater.decimalMutiple((+qty), (+C_Numerator) / (+C_Denominator)),
                        C_Mode = plotInfo.workstation_detail[0].C_Mode,
                        C_Accuracy = Math.pow(10, plotInfo.workstation_detail[0].C_Accuracy || 0) || 1;
                    if (C_Mode == '0') {
                        //無條件進位
                        QTYACIO = Math.ceil(QTYACIO * C_Accuracy) / C_Accuracy;
                    } else if (C_Mode == '1') {
                        //無條件捨��?
                        QTYACIO = Math.floor(QTYACIO * C_Accuracy) / C_Accuracy;
                    }
                    return QTYACIO;
                }

                //確認是否需要多人產量登入數量重��?
                function reCalcMultipleQty(dialog, callback) {
                    if (dialog.OutQtyOption == '1' || dialog.OutQtyOption == '2') {
                        //出站數量有異動，是否要重計多人產量登入數��?
                        $rootScope.showConfirm($filter('translate')('mobile01.checkout.msg.is_recalculate_multiple_qty'), function (confirmDialog) {
                            confirmDialog.hide();
                            multipleRecalculateImp(dialog, function () {
                                if (callback)
                                    callback();
                            });
                        }, function (confirmDialog) {
                            confirmDialog.hide();
                            if (callback)
                                callback();
                        });
                    } else if (dialog.OutQtyOption == '3') {
                        var max_labor_qty = 0;
                        dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function (labor) {
                            if (max_labor_qty < labor.qty) {
                                max_labor_qty = labor.qty;
                            }
                        });

                        if (dialog.plotInfo.workstation_detail[0].QTYACIO < max_labor_qty) {
                            $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.chkout_ls_multiple_qty')); //出站數量小於多人產量登入數量，請重新維護��?
                            multipleRecalculateImp(dialog, function () {
                                if (callback)
                                    callback();
                            });
                        } else {
                            if (callback)
                                callback();
                        }
                    } else {
                        multipleRecalculateImp(dialog, function () {
                            if (callback)
                                callback();
                        });
                    }
                }

                //多人產量登入數量重計
                function multipleRecalculateImp(dialog, callback) {
                    var QTYACIO = dialog.plotInfo.workstation_detail[0].QTYACIO; //出站後數��?出站-不良-短少+多餘)
                    var labor_detail = dialog.plotInfo.workstation_detail[0].labor_detail;
                    let good_qty = dialog.plotInfo.good_qty;
                    if (dialog.OutQtyOption == '0') {
                        //0: 預設(每人數量=出站數量)
                        if (labor_detail && labor_detail.length > 0) {
                            for (var index = 0; index < labor_detail.length; index++) {
                                labor_detail[index].qty = good_qty;
                            }
                        }
                    } else if (dialog.OutQtyOption == '1') {
                        // 1: 均分(每人數量 = 出站數量/人員總數)
                        multipleRecalculate(good_qty, labor_detail, function (index, assigned_qty) {
                            // 20230522 modify by 文蔚 for M#134294 多人產量登入，當人數 > 數量時，會以小數點後兩位繼續計算
                            if (labor_detail.length > good_qty) {
                                return (good_qty / labor_detail.length).toFixed(2);
                            } else {
                                if (index < (labor_detail.length - 1)) {
                                    return Math.floor(good_qty / labor_detail.length);
                                } else {
                                    return $calculater.decimalSub(good_qty, assigned_qty); //剩下未分配的數量全塞給最後一��?
                                }

                            }
                        });
                    } else if (dialog.OutQtyOption == '2') {
                        // 2: 按在線時間分��?每人數量 = 出站數量*人員工時/總人��?
                        var total_labor_time = 0; //總人��?
                        labor_detail.forEach(function (labor) {
                            total_labor_time = $calculater.decimalAdd(total_labor_time, labor.labor_time);
                        });
                        labor_detail = $filter('orderBy')(dialog.plotInfo.workstation_detail[0].labor_detail, 'labor_time'); //用工時排序，確保工時多的人排在最��?

                        if (total_labor_time > 0) {
                            multipleRecalculate(good_qty, labor_detail, function (index, assigned_qty) {
                                if (index < (labor_detail.length - 1)) {
                                    return Math.floor($calculater.decimalMutiple(good_qty, labor_detail[index].labor_time) / total_labor_time);
                                } else {
                                    return $calculater.decimalSub(good_qty, assigned_qty); //剩下未分配的數量全塞給最後一��?
                                }
                            });
                        } else {
                            //工時總和=0，採用均分(每人數量 = 出站數量/人員總數)
                            multipleRecalculate(good_qty, labor_detail, function (index, assigned_qty) {
                                if (index < (labor_detail.length - 1)) {
                                    return Math.floor(good_qty / labor_detail.length);
                                } else {
                                    return $calculater.decimalSub(good_qty, assigned_qty); //剩下未分配的數量全塞給最後一��?
                                }
                            });
                        }
                    } else if (dialog.OutQtyOption == '3') {
                        // 3: 全手動輸入(每人數量 = 0)
                        multipleRecalculate(good_qty, labor_detail, function (index, assigned_qty) {
                            return 0;
                        });
                    }
                    if (callback)
                        callback();
                }

                //多人產量登入數量重計
                function multipleRecalculate(QTYACIO, labor_detail, getQty) {
                    var qty = 0; // 每人分到的數量
                    var assigned_qty = 0; //已分配的數量

                    if (labor_detail && labor_detail.length > 0) {
                        //20210310 Modify by chenshibo for#89117：均分出站量，上工4个人，出站2件，出站时多人产量默认为1，1,1，-1
                        for (var index = 0; index < labor_detail.length; index++) {
                            if (QTYACIO <= assigned_qty) {
                                qty = 0;
                            }
                            else {
                                qty = getQty(index, assigned_qty);
                            }
                            labor_detail[index].qty = qty;
                            assigned_qty = $calculater.decimalAdd(assigned_qty, qty);
                        }
                    }
                }

                function check_checkout_qty(num, dialog, target, calcDialog) {
                    if ((+num) == 0 && dialog.OutQtyAllowZero == '0') {
                        $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.The_checkout_qty_cannot_be_zero'));
                    } else if ((+num) > dialog.plotInfo.workstation_detail[0].check_out_qty) {
                        $rootScope.showAlert($filter('translate')('mobile01.checkout.qty') + num + $filter('translate')('mobile01.checkout.cannt_greater_than') + dialog.plotInfo.workstation_detail[0].check_out_qty);
                    } else {
                        dialog.plotInfo.qty = num;
                        //良品 = 出站數量 - 不良品 - 短少 + 多餘
                        dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                        //2018051601 modify by Dustdusk for M#45925:
                        //物料使用��?= 『良品��?+ 『不良品��?+ 『短少��?= 『出站數量��?+ 『多餘��?
                        // 20220122 modify by Alan for M#104045: 物料耗用數量計算依系統參數決定是否需計算短少或是多餘的生產數
                        var MTL_Includes_ExcessLoss = dialog.plotInfo.MTL_Includes_ExcessLoss === undefined ? true : dialog.plotInfo.MTL_Includes_ExcessLoss;
                        // 20231123 modify by wenwei for M#142054: [sMES]物料數量扣減異常[松讚]
                        // 物料使用量
                        var sum_qty = MTL_Includes_ExcessLoss
                            // 良品 + 不良 + 短少 - 多餘
                            ? (+plotInfo.good_qty) + (+plotInfo.total_abnormal_qty) + (+plotInfo.total_lack_qty) - (+plotInfo.total_surplus_qty)
                            // 良品 + 不良
                            : (+plotInfo.good_qty) + (+plotInfo.total_abnormal_qty);
                        reCalcMaterialUseQty(sum_qty, dialog);
                        //2018051601 modify by Dustdusk for M#45925:
                        //如果良品��?= 『出站數量��?- 『不良品��?- 『短少��?+ 『多餘��?小於0則清空例外原��?
                        if (((+num) + dialog.plotInfo.total_surplus_qty) < ((+dialog.plotInfo.total_abnormal_qty) + (+dialog.plotInfo.total_lack_qty))) {
                            calcDialog.hide();
                            var total_abnormal_qty = dialog.plotInfo.total_abnormal_qty;
                            var total_surplus_qty = dialog.plotInfo.total_surplus_qty;
                            var total_lack_qty = dialog.plotInfo.total_lack_qty;
                            dialog.plotInfo.total_abnormal_qty = 0;
                            dialog.plotInfo.total_surplus_qty = 0;
                            dialog.plotInfo.total_lack_qty = 0;
                            dialog.badReasonInfo = [];
                            dialog.plotInfo.good_qty = num;
                            //20231120 modify by wangqq for M#0148297:生產批總數567 出站良品4+不良品563 當修改出站數量為562<不良品數，不良則會歸0，但出站後生產批數量仍是0 是5
                            //20231124 modify by wangqq for M#0148297:出站后生产批数量=生产品数量-出站数
                            dialog.leftqty = $calculater.decimalSub((+dialog.plotInfo.workstation_detail[0].check_out_qty), (+num));
                            dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                            $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.qty_less_than_abnormal_qty', { abnormal_qty: (total_abnormal_qty + total_lack_qty - total_surplus_qty) }), function () {
                                //多人產量登入
                                reCalcMultipleQty(dialog, function () { });
                            });
                        } else {
                            //2018051601 modify by Dustdusk for M#45925:
                            //良品��?= 『出站數量��?- 『不良品��?- 『短少��?+ 『多餘��?

                            //20211029 modify by 翰鴻 for Mantis#97211:
                            //出站後生產批數量 = 生產批現況數量 - 良品 - 不良品 
                            //良品 = 輸入量
                            var lastqty;

                            lastqty = plotInfo.workstation_detail[0].CheckOutPlotQty;
                            //20231023 modify by wangzy for M#0148297: [sMES]作業區工作平台，出站後生產批數量為負數[格斯]
                            dialog.leftqty = $calculater.decimalSub((+lastqty), (+num));
                            dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+num), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                            //20220525 modify by wangzy M#0112778: 單位轉換後TBLWIPCONT_RESOURCE數量不準確
                            dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO((+num), dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                            calcDialog.hide();
                            //多人產量登入
                            reCalcMultipleQty(dialog, function () { });
                        }
                        angular.element(target).removeClass('is-focus');
                    }
                }

                (function openDialog(){
                    $mdDialog.dialog(
                        'module/moduleMobile/program/mobile01/CheckOut.tmp.html',
                        function (dialog) {
                            return {
                                OutQtyAllowZero: '0', // 出站量可為零 0: 不允��?1: 允許
                                status_list: [{ name: $filter('translate')('mobile01.checkout.status_badReason'), select:true}, { name: $filter('translate') ('mobile01.checkout.status_multiple') }],
                                plotInfo: options.item, // 修正成跟PC版一樣的名稱，方便後續維護
                                badItem:{reason_type:'', reason_no:''},
                                production_inf_type:options.item.production_inf_type,//判斷生產訊息功能要不要打開
                                badItemList: options.item.workstation_detail[0].abnormal_detail,// 20210915 modify by chenshibo for#0100013: 巡检不良，PDA出站报工时未体现巡检不良数量
                                production_inf_detail:[],
                                beforeShown:function(){
                                    if(+dialog.production_inf_type != 0){
                                        dialog.status_list.push({ name: $filter('translate') ('mobile01.checkout.status_information') });
                                        dialog.production_inf_detail = options.item.production_inf_detail;
                                    }
                                    $MMWService.sendToServer({//呼叫取得不良原因服務
                                        uri : 'ServicesSTD.Module_WIP.qc_reason_basis_info_get',
                                        content : {
                                            op_no: options.item.workstation_detail[0].op_no,
                                            login_employee_no: config.cache.account,
                                            machine_no: options.machine_no,
                                            plot_no: options.item.workstation_detail[0].plot_no
                                        },
                                        success : function(data){
                                            dialog.bad_type_list = genBadType(data.qc_reason_basis);//不良原因類型
                                            dialog.bad_code_list = data.qc_reason_basis;//帶入不良原因
                                        }
                                    });
                                    equipmentBasisGet(function (data) {
                                        dialog.OutQtyDefinition = data.outqtydefinition || '0';
                                        dialog.OutQtyAllowZero = data.outqtyallowzero || '0';
                                        dialog.OutQtyOption = data.outqtyoption || '0';
                                        //多人產量登入
                                        multipleRecalculateImp(dialog, function(){});
                                    });
                                },
                                back:function(){
                                    dialog.hide();
                                },
                                trackOutInputQty: function(event){
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function(num,calcDialog){
                                        if ((+num) != dialog.plotInfo.qty) {
                                            check_checkout_qty(num, dialog, target, calcDialog);
                                        } else {
                                            calcDialog.hide();
                                        }
                                        getPriceSum(); 
                                        getPriceSumByLabor();
                                    },function(calcDialog){
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum : dialog.plotInfo.qty,
                                        decimal : true                  //M#97342 出站數量開窗添加小數點
                                    });
                                },
                                trackInputQty: function (event, type, qty) {
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function (num, calcDialog,qty) {
                                        if (type == "labor_hours") {
                                            dialog.plotInfo.workstation_detail[0].labor_hours = num;
                                        } else {
                                            dialog.plotInfo.workstation_detail[0].machine_hours = num;
                                        }
    
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
    
                                    }, function (calcDialog) {
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum: qty,
                                        decimal: true
                                    });
                                },
                                trackLabor_hours_InputQty: function (event, item, qty) {
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function (num, calcDialog, qty) {
                                        item.labor_time = num;
    
                                        var total_labor_hours = 0;
                                        //汇总人时
                                        if (dialog.plotInfo.workstation_detail[0].labor_detail.length > 0)
                                        {
                                            dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function (item)
                                            {
                                                total_labor_hours += parseFloat(item.labor_time);
                                            });
                                        }
                                        dialog.plotInfo.workstation_detail[0].labor_hours = total_labor_hours;
    
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
    
                                    }, function (calcDialog) {
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum: qty,
                                        decimal: true
                                    });
                                },
                                trackLabor_qty_InputQty: function (event, item, qty) {
                                    // 20240225 add by Alan for M#156794: 增加多人數量可修改
                                    var target = event.currentTarget;
                                    angular.element(target).addClass('is-focus');
                                    $calculater.open(function (num, calcDialog, qty) {
                                        const QTYACIO = dialog.plotInfo.workstation_detail[0].QTYACIO;
                                        if ((+num) > (+QTYACIO)) {
                                            $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.do_not_exceed') + QTYACIO);
                                            angular.element('#calculater_display').focus();
                                            return;
                                        } 
                                        
                                        item.qty = num;
                                        getPriceSumByLabor(dialog.plotInfo);
    
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    }, function (calcDialog) {
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum: qty,
                                        decimal: true
                                    });
                                },
                                loadBadTypeList: function(){
                                    $rootScope.showSelect({
                                        label: 'reason_sub_type',
                                        code: 'reason_type',
                                        selectCode: dialog.badItem.bad_type,
                                        list: dialog.bad_type_list,
                                        confirm: function (item, radioDialog) {
                                            radioDialog.hide();
                                            if(dialog.badItem.type_no != item.reason_type){
                                                dialog.badItem.type_no = item.reason_type;
                                                dialog.badItem.type_name = item.reason_sub_type;
                                                dialog.badItem.reason_no = '';
                                                dialog.badItem.reason_name = '';
                                            }
                                        }
                                    });
                                },
                                switchInit: function(item){
                                    if(!item.productioninf_value){
                                        item.productioninf_value = '0';
                                    }
                                },
                                switchClick:function(item){
                                    if(item.productioninf_value === '0'){
                                        item.productioninf_value = '1';
                                    }else{
                                        item.productioninf_value = '0'
                                    }
                                },
                                add: function (reason_type) {
                                    const _bad_code_list = dialog.bad_code_list.filter((item) => item.reason_type == reason_type);
                                    loadBadNoList(_bad_code_list, (data) => {
                                        const _filledList = data
                                            .filter((item) => item.qty > 0)
                                            .map((item) => {
                                                return {
                                                    plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                                                    reason_type: item.reason_type,
                                                    abnormal_type_name: item.type_name,
                                                    abnormal_no: item.reason_no,
                                                    abnormal_name: item.reason_name,
                                                    defect_qty: item.qty,
                                                };
                                            });
                                        const _badItemList = dialog.badItemList.concat(_filledList);

                                        let badAllQty = _badItemList.reduce((acc, cur) => acc + (+cur.defect_qty), 0)
                                        if (badAllQty > (+dialog.plotInfo.qty)) {
                                            $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.abnormal_qty_larger_than_qty') + dialog.plotInfo.qty);
                                            return false;
                                        }

                                        dialog.badItemList = angular.copy(_badItemList);

                                        let total_surplus_qty = 0; //多餘
                                        let total_lack_qty = 0; //短少
                                        let total_abnormal_qty = 0; //報廢

                                        dialog.badItemList.forEach(function (info) {
                                            if (info.reason_type == '11') {
                                                total_surplus_qty = $calculater.decimalAdd(total_surplus_qty, (+info.defect_qty));
                                            } else if (info.reason_type == '12') {
                                                total_lack_qty = $calculater.decimalAdd(total_lack_qty, (+info.defect_qty));
                                            } else {
                                                total_abnormal_qty = $calculater.decimalAdd(total_abnormal_qty, (+info.defect_qty));
                                            }
                                        });

                                        dialog.plotInfo.total_abnormal_qty = total_abnormal_qty;
                                        dialog.plotInfo.total_surplus_qty = total_surplus_qty;
                                        dialog.plotInfo.total_lack_qty = total_lack_qty;
                                        //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                        dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));

                                        // 多人產量重計
                                        _QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                        if (_QTYACIO != dialog.plotInfo.workstation_detail[0].QTYACIO) {
                                            dialog.plotInfo.workstation_detail[0].QTYACIO = _QTYACIO;
                                            //多人產量登入
                                            reCalcMultipleQty(dialog, () => {});
                                        }

                                        return true
                                    });
                                },
                                //刪除不良原因
                                remove : function(item){
                                    if (item.reason_type == '11') {
                                        dialog.plotInfo.total_surplus_qty = (+dialog.plotInfo.total_surplus_qty) - (+item.defect_qty);
                                    } else if (item.reason_type == '12') {
                                        dialog.plotInfo.total_lack_qty = (+dialog.plotInfo.total_lack_qty) - (+item.defect_qty);
                                    } else {
                                        dialog.plotInfo.total_abnormal_qty = (+dialog.plotInfo.total_abnormal_qty) - (+item.defect_qty);
                                    }
                                    //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                    dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                                    _QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                    if (_QTYACIO != dialog.plotInfo.workstation_detail[0].QTYACIO) {
                                        dialog.plotInfo.workstation_detail[0].QTYACIO = _QTYACIO;
                                        //多人產量登入
                                        reCalcMultipleQty(dialog, () => {});
                                    }
                                    dialog.badItemList.splice(dialog.badItemList.indexOf(item), 1);
                                },
                                confirm:function(){
                                    AccLifeCheck(options.machine_no, dialog, function(){
                                        ProductionParametersCheckProcess(dialog);
                                    });
                                },
                                changeTab:function(tab_index){
                                    dialog.status_list.forEach(function (data, index) {
                                        if(index == tab_index){
                                            data.select = true;
                                        } else {
                                            data.select = false;
                                        }
                                    });
                                }
    
                            };
                        }
                    );
                })();       
            };
        }
    ]);
});
